﻿using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace BigMailer
{
	public partial class UploadingControl : UserControl, IDisposable
	{
		private DispatcherTimer timer;
		private Uploader uploader;

		public UploadingControl(string fileName)
		{
			InitializeComponent();

			uploader = new Uploader( fileName );
			progressBar.Minimum = 0;
			progressBar.Maximum = uploader.FileSize;

			timer = new DispatcherTimer(
				TimeSpan.FromMilliseconds( 100 ),
				DispatcherPriority.Normal,
				timer_Tick,
				this.Dispatcher );

			timer.Start();

			this.tbStatus.Text = "Uploading " + Path.GetFileName( fileName ) + " ...";
		}

		public SendStatus Status
		{
			get { return uploader.Status; }
		}

		public string FileName
		{
			get { return uploader.FileName; }
		}

		private void timer_Tick(object sender, EventArgs e)
		{
			switch ( uploader.Status )
			{
				case SendStatus.Active:
					{
						long position = uploader.Position;
						TimeSpan dt = DateTime.Now - uploader.StartTime;
						double secs = Math.Max( dt.TotalSeconds, 0.001 );
						double rateKb = position / secs / 1024.0;
						progressBar.Value = position;

						if ( rateKb < 1000 )
						{
							tbUploadRate.Text = rateKb.ToString( "N0" ) + " KB/sec";
						}
						else
						{
							tbUploadRate.Text = (rateKb/1000).ToString( "N0" ) + " MB/sec";
						}
					}
					break;
				case SendStatus.Uploaded:
					{
						linkCancelContainer.Visibility = Visibility.Collapsed;
						linkFinalUrlContainer.Visibility = Visibility.Visible;
						tbStatus.Text = "Uploaded " + Path.GetFileName( uploader.FileName );
						uploader.Dispose();
						timer.Stop();
					}
					break;
				case SendStatus.Cancelled:
					{
						tbStatus.Text = "Cancelled " + Path.GetFileName( uploader.FileName );
						linkCancelContainer.Visibility = Visibility.Hidden;
						timer.Stop();
					}
					break;
				case SendStatus.Errored:
					{
						tbStatus.Text = "Error: " + uploader.Error.Message;
						linkCancelContainer.Visibility = Visibility.Hidden;
						timer.Stop();
					}
					break;
			}
		}

		private void linkCancel_Click(object sender, RoutedEventArgs e)
		{
			uploader.Cancel();
			tbStatus.Text = "Cancelled";
			linkCancel.IsEnabled = false;
		}

		public void Dispose()
		{
			uploader.Dispose();
		}

		private void linkFinalUrl_Click(object sender, RoutedEventArgs e)
		{
			UiCore.ShowFinalLink( uploader.FinalUrl );
		}
	}
}